package com.itheima.tlias.filter;

import com.itheima.tlias.utils.CurrentHolder;
import com.itheima.tlias.utils.JwtUtils;
import io.jsonwebtoken.Claims;
import org.apache.http.HttpStatus;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Map;


@Component
public class TokenInterceptor implements HandlerInterceptor {
    @Autowired
    private JwtUtils jwtUtils;

    public boolean preHandle(HttpServletRequest request,
                             HttpServletResponse response, Object handler) throws Exception {
        //获取令牌
        String token = request.getHeader("token");
        if (token == null) {
            response.setStatus(401);
            return false;
        }
        try {
            Map<String, Object>  claims= jwtUtils.parseJWT(token);
            Integer empId = Integer.valueOf(claims.get("id").toString());
            CurrentHolder.setCurrentId(empId);

        } catch (Exception e) {
            response.setStatus(401);
            response.setStatus(HttpStatus.SC_UNAUTHORIZED);
            return false;
        }
        return true;

    }

}
